package com.dtranx.tools.locale.utils;

import com.dtranx.tools.commons.vo.AbstractLocal;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class LocalUtils extends AbstractLocal {

    private Map<String, Map<String, String>> localeMap = new HashMap<>();

    public Map<String, Map<String, String>> getLocaleMap() {
        return localeMap;
    }

    public void setLocaleMap(Map<String, Map<String, String>> localeMap) {
        this.localeMap = localeMap;
    }

    private static String LOCALE = "locale";

    private static String MESSAGE = "message_";

    @Override
    public String getMessage(Integer code, Object... args) {
        return getMessageByLocale(code,getLocale(),args);
    }

    @Override
    public String getMessageByLocale(Integer code, String locale, Object... args) {
        Map<String, String> map = CollectionUtils.isEmpty(localeMap) ? new HashMap<>() : localeMap.get(MESSAGE + locale);
        String msg = map.get(String.valueOf(code));
        return args == null ? msg : String.format(StringUtils.isEmpty(msg) ? "" : msg, args);
    }

    @Override
    public String getLocale() {
        String locale = "zh";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(attributes)) {
            HttpServletRequest request = attributes.getRequest();
            if (!ObjectUtils.isEmpty(request)) {
                locale = request.getHeader(LOCALE) == null ? "zh" : request.getHeader(LOCALE).toLowerCase();
            }
        }
        return locale;
    }
}
